package com.itshen.handler;

import com.itshen.entity.User;
import com.itshen.repository.UserRepository;
import com.itshen.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @author: stephen.shen
 * @create: 2018-12-07 10:06
 */
@Component
public class UserHandler {

    @Autowired
    UserRepository repository;

    /**
     * 查询所有用户
     *
     * @return
     */
    public Mono<ServerResponse> getAll(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(repository.findAll(), User.class);
    }

    /**
     * 创建用户
     */
    public Mono<ServerResponse> create(ServerRequest request) {
        Mono<User> userMono = request.bodyToMono(User.class);
        return userMono.flatMap(u -> {
            // 校验代码需要放在这里
            CheckUtil.checkName(u.getName());
            return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(repository.insert(u), User.class);
        });
    }

    /**
     * 删除用户
     *
     * @param request
     * @return
     */
    public Mono<ServerResponse> deleteUserById(ServerRequest request) {
        String id = request.pathVariable("id");
        return repository.findById(id)
                .flatMap(
                        user -> this.repository.delete(user).then(ServerResponse.ok().build()))
                .switchIfEmpty(ServerResponse.notFound().build());
    }
}
